package com.zhangdi.demo.es.service;

import com.zhangdi.demo.es.entity.CompanyDoc;
import com.zhangdi.demo.es.esrepository.ESUserRepository;
import com.zhangdi.mserver.searchcli.MSearchRequest;
import com.zhangdi.mserver.searchcli.enums.MatchType;
import com.zhangdi.mserver.searchcli.page.Page;
import com.zhangdi.mserver.searchcli.page.Pageable;
import com.zhangdi.mserver.searchcli.repository.ClientApi;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * Created by zhangdi on 2020/07/10 11:06:04.
 */

@Service
public class EsUserServiceImpl implements ESUserService {
    @Autowired
    ESUserRepository userRepository;

    @Resource
    RestHighLevelClient client;

    @Autowired
    ClientApi<CompanyDoc> clientApi;

    @Override
    public List<CompanyDoc> findAll() {
        return CollectionUtils.iterableAsArrayList(userRepository.findAll());
    }

    @Override
    public Page<CompanyDoc> findByKeyValue(Map<String, Object> params) {
        Page<CompanyDoc> pager = new Page<>();

        List<MSearchRequest> companyReq = new ArrayList<>();
        MSearchRequest r1 = new MSearchRequest();
        r1.setFieldName("areaId");
        r1.setValue(params.get("areaId"));
        r1.setMatchType(MatchType.term);
        companyReq.add(r1);

        Pageable<List<MSearchRequest>> pageable = new Pageable<>();
        pageable.setT(companyReq);
        pageable.setNo(0);
        pageable.setSize(20);

        pager = clientApi.search(pageable, CompanyDoc.class, "");

        return pager;
    }

    @Transactional
    @Override
    public CompanyDoc save(CompanyDoc company) {
        return userRepository.save(company);
    }

    @Transactional
    @Override
    public void save(List<CompanyDoc> list) {
        userRepository.saveAll(list);
    }
}
